<template>
  <el-dialog title="修改密码" destroy-on-close width="500px" v-model="visibleModelValue">
    <template #default>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="80px"
        class="jxtech-header-dropdown-pwd"
      >
        <el-form-item label="当前密码" prop="oldPass">
          <el-input :status-icon="false" v-model="ruleForm.oldPass" type="password" autocomplete="on" show-password></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPass">
          <el-input :status-icon="false" v-model="ruleForm.newPass" type="password" autocomplete="off" show-password></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="checkNewPass" autocomplete="off" show-password>
          <el-input
            :status-icon="false"
            v-model="ruleForm.checkNewPass"
            type="password"
            @keydown.enter="submitForm(ruleFormRef)"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <JxtechCancelButton @click="resetForm(ruleFormRef)">
          {{ $t("button.cancel") }}
        </JxtechCancelButton>
        <JxtechOkButton @click="submitForm(ruleFormRef)" :loading="submitLoading">
          {{ $t("button.ok") }}
        </JxtechOkButton>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, Ref, reactive } from "vue";
import type { ElForm } from "element-plus";
import userBeanServiceApi from "@/api/modules/org/bean/user-bean";
import { messageSuccessTip } from "@/utils/message-config";
let submitLoading: Ref<boolean> = ref(false);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits<{
  (e: "update:visible", val: boolean): void;
}>();

const visibleModelValue = computed({
  get() {
    return props.visible;
  },
  set(v) {
    emit("update:visible", v);
  }
});
type FormInstance = InstanceType<typeof ElForm>;
const ruleFormRef = ref<FormInstance | null>(null);
const pwdValidState = reactive({
  // 旧密码验证
  validatePass: (rule: any, value: any, callback: any) => {
    if (value === "") {
      callback(new Error("请输入当前密码!"));
    } else {
      if (ruleForm.newPass !== "") {
        if (!ruleFormRef.value) return;
        ruleFormRef.value.validateField("checkPass", () => null);
      }
      callback();
    }
  },
  //pwdReg: /^(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*]{8,}$/,
  //密码必须为 大小写字母 以及数字三种情况组合 长度为8-15
  pwdReg: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}$/,
  // pwdReg: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]])[A-Za-z\d`~!@#$%^&*()_+<>?:"{},.\/\\;'[\]]{8,}$/,
  // 新密码输入第一次 规则
  validatePass2: (rule: any, value: any, callback: any) => {
    if (value === "") {
      callback(new Error("请输入新密码!"));
    } else if (value === ruleForm.oldPass) {
      callback(new Error("新旧密码不能相同!"));
    } else if (!value.match(pwdValidState.pwdReg)) {
      callback(new Error("用户密码必须由大写，小写字母以及数字三种字符组成，且长度为8-15之间!"));
    } else {
      callback();
    }
  },
  // 重复确认新密码规则
  checkPass: (rule: any, value: any, callback: any) => {
    if (!value) {
      return callback(new Error("请再次确认新密码!"));
    } else if (value !== ruleForm.newPass) {
      return callback(new Error("两次输入密码不一致!"));
    } else {
      callback();
    }
  }
});
const ruleForm = reactive({
  oldPass: "",
  newPass: "",
  checkNewPass: ""
});

const rules = reactive({
  oldPass: [{ validator: pwdValidState.validatePass, trigger: "blur", required: true }],
  newPass: [
    { validator: pwdValidState.validatePass2, trigger: "blur", required: true },
    {
      min: 8,
      max: 20,
      message: "密码长度应在8-20位之间",
      trigger: "blur"
    }
  ],
  checkNewPass: [{ validator: pwdValidState.checkPass, trigger: "blur", required: true }]
});
const resetForm = (formEl: InstanceType<typeof ElForm> | undefined) => {
  if (!formEl) return;
  visibleModelValue.value = false;
  formEl.resetFields();
};
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      userBeanServiceApi
        .changePass(null, {
          newPass: ruleForm.newPass,
          oldPass: ruleForm.oldPass
        })
        .then(res => {
          messageSuccessTip("密码修改成功!");
        })
        .catch(err => {
          console.error(err);
        });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
.jxtech-header-dropdown-pwd {
  .el-form-item:last-child {
    margin-bottom: 0;
  }
}
</style>
